package com.itobase.statusDetect.Service.impl;

import com.itobase.statusDetect.Model.Organization;
import com.itobase.statusDetect.Model.Student;
import com.itobase.statusDetect.Model.Teacher;
import com.itobase.statusDetect.Model.User;
import com.itobase.statusDetect.Repository.OrganizationRepository;
import com.itobase.statusDetect.Repository.StudentRepository;
import com.itobase.statusDetect.Repository.TeacherRepository;
import com.itobase.statusDetect.Repository.UserRepository;
import com.itobase.statusDetect.Util.ExcelUtil;
import com.itobase.statusDetect.Util.ListUtil;
import com.itobase.statusDetect.Util.Message;
import com.itobase.statusDetect.template.Constant;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.itobase.statusDetect.Util.ExcelUtil.isExcel2007;

/**
 * @author htyu
 * @date 2019/5/9
 */
@Service
public class ExcelService {

    @Autowired
    OrganizationRepository organizationRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    TeacherRepository teacherRepository;

    @Autowired
    StudentRepository studentRepository;

    /**
     * 判断组织架构是否存在
     * @param str
     * @return
     */
    public HashMap<String,Object> isExist(String str){
        String[] orga = str.split("/");
        HashMap<String,Object> map = new HashMap<>();
        Organization organization;
        String organizationID = "";
        Boolean flag = true;
        for(String subOrga:orga){
            organization = organizationRepository.findByName(subOrga);
            if(organization==null){
                flag = false;
                break;
            }
            organizationID = organization.getId();
        }
        map.put("id",organizationID);
        map.put("flag",flag);
        return map;
    }

    public List<String> readUserExcel(MultipartFile file) throws IOException {
        InputStream is = file.getInputStream();
        String fileName = file.getOriginalFilename();
        Workbook book;
        List<User> list_user = new ArrayList<>();
        List<Teacher> list_teacher = new ArrayList<>();
        List<Student> list_student = new ArrayList<>();
        List<String> list_error = new ArrayList<>();
        Row row;
        if (isExcel2007(fileName)) {
            book = new XSSFWorkbook(is);
        } else {
            book = new HSSFWorkbook(is);
        }
        Sheet sheet = book.getSheetAt(0);
        Cell cell;
        String name,number,phone,type,organization;
        for(int i = 5, j = 0; i <= sheet.getLastRowNum(); i++){
            row = sheet.getRow(i);
            cell = row.getCell(0);
            cell.setCellType(CellType.STRING);
            number = cell.getStringCellValue();
            name = row.getCell(1).getStringCellValue();
            cell = row.getCell(2);
            cell.setCellType(CellType.STRING);
            phone = cell.getStringCellValue();
            type = row.getCell(3).getStringCellValue();
            organization = row.getCell(4).getStringCellValue();
            HashMap<String,Object> map = isExist(organization);
            Boolean flag = (Boolean) map.get("flag");
            String id = (String) map.get("id");
            if(flag){
                if(type.equals(Constant.STUDENT)){
                    Student student = new Student();
                    student.setName(name);
                    student.setNumber(number);
                    student.setOrganizationID(id);
                    student.setPassword("123456");
                    student.setPhone(phone);
                    list_student.add(student);
                }
                else if(type.equals(Constant.ADMIN)){
                    User user = new User();
                    user.setNumber(number);
                    user.setPassword("123456");
                    user.setName(name);
                    user.setPhone(phone);
                    user.setOrganizationID(id);
                    list_user.add(user);
                }else if(type.equals(Constant.TEACHER)){
                    Teacher teacher = new Teacher();
                    teacher.setName(name);
                    teacher.setNumber(number);
                    teacher.setOrganizationID(organization);
                    teacher.setPassword("123456");
                    teacher.setPhone(phone);
                    list_teacher.add(teacher);
                }
            }else{
                list_error.add("表格内第"+i+"行，"+name+"的组织架构不存在，请先在系统内新建该组织架构");
            }
        }
        list_user = ListUtil.removeDuplicateWithOrder(list_user);
        User user_1;Student student_1;Teacher teacher_1;
        for(User user:list_user){
            user_1 = userRepository.findByNumber(user.getNumber());
            if(user_1==null) {
                userRepository.save(user);
            }
        }
        list_teacher = ListUtil.removeDuplicateWithOrder(list_teacher);
        for(Teacher teacher:list_teacher){
            teacher_1 = teacherRepository.findByNumber(teacher.getNumber());
            if(teacher_1==null) {
                teacherRepository.save(teacher);
            }
        }
        list_student = ListUtil.removeDuplicateWithOrder(list_student);
        for(Student student:list_student){
            student_1 = studentRepository.findByNumber(student.getNumber());
            if(student_1==null) {
                studentRepository.save(student);
            }
        }
        if(list_error.size()==0){
            list_error.add("全部导入成功");
        }else{
            list_error.add("其余全部导入成功");
        }
        return list_error;
    }

    public String export2007(HttpServletResponse response) {
        try {
            Resource resource = new ClassPathResource("user.xlsx");
            File file = resource.getFile();
            InputStream is = new FileInputStream(file);
            Workbook book = new XSSFWorkbook(is);
            writeToResponse(response,book);
        }catch (IOException e){
            e.printStackTrace();
        }
        return "导出成功";
    }

    public  void writeToResponse(HttpServletResponse response, Workbook workbook) {
        if (workbook != null) {
            try {
                //String fileName = new String("人员导入模板".getBytes(), StandardCharsets.UTF_8)  + ".xlsx";
                String fileName = "人员导入模板.xlsx";
                String headStr = "attachment;filename=" + fileName;
                response.setContentType("APPLICATION/OCTET-STREAM");
                response.setHeader("Content-Disposition", headStr);
                OutputStream out = response.getOutputStream();
                workbook.write(out);
                workbook.close();
                out.flush();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
